#include <ustdio.h>
#include <uprocess.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "rc.h"
uint32_t buf = 0;
char inbuf[20];
int driverrc_cb(char *path){
	uexec(path);
	return 1;
}

int main(int argc,char **argv){
	char *hello = "Hello";
	printf("\nINIT V0.0.4 running.\n\nPipe self-test:\nWriting %s to pipe...\n",hello);
	int pipe_fd = umkloop(40);
	uwrite(pipe_fd,(uint8_t*)hello,strlen(hello));
	printf("Reading from pipe (%x bytes)...\n",uavail(pipe_fd));
	uread(pipe_fd,(uint8_t*)inbuf,uavail(pipe_fd));
	printf("Data: %s\n",inbuf);
	printf("\n\nMounting devfs on /dev...");
	if (!u_mount("/dev","/dev","devfs")){
		printf("FAILED (0x%x)\n",errno);
		return 0;
	}
	printf("OK\n");
	printf("Loading drivers...\n");
	if (exec_rc("/etc/drivers.rc",driverrc_cb) != 0){
		printf("INIT ERROR: Failed to load all drivers!\n");
		if (errno == ENOENT)
			printf("           /etc/drivers.rc not found!\n");
	}
	printf("\nProcess list: \n");
	int procfile_fd = uopen("/dev/procfile",0,0);
	if(procfile_fd == -1){
		printf("Error opening procfile: %i\n",errno);
	} else {
		while(1){
			uint8_t buf = 0;
			if (uread(procfile_fd,&buf,1) == 1)
				uwrite(1,&buf,1);
			else
				break;
		}
		uclose(procfile_fd);
	}
	printf("\n\n");
	printf("Catting input:\n");
	while(1){
		uint8_t buf = 0;
		uread(0,&buf,1);
		uwrite(1,&buf,1);
	}
}